<?php

class IndexAction extends CommonAction {
    public function index()
	{
		header("Content-Type:text/html; charset=utf-8");
		header("HTTP/1.1 301 Moved Permanently");
		header("Location:https://www.baidu.com/s?ie=UTF-8&wd=MISONE-POS");
	}
	
	public function ping()
	{
		header("Content-Type:text/html; charset=utf-8");
        
		$p = $this->getObjData();
		
		$this->ret('1','success');
	}
	
	public function login()
	{
        header("Content-Type:text/html; charset=utf-8");
        
		$p = $this->getObjData();
		
		//file_put_contents("debug.txt",date('Y-m-d H:i:s')."--------".serialize($p)."----------\r\n",FILE_APPEND);
		
		$model = M('User');
		$_list = $model->where(array('status_flg'=>'Y','role'=>array('in',array('admin','pos')),'username'=>$p['username'],'password'=>$p['passwd']))->find();
		if($_list)
		{
			$re_map['id'] = $_list['id'];
			$re_data['logintime'] = time();
			$re_data['loginip'] = get_client_ip();
			$model->data($re_data)->where($re_map)->save();
			//file_put_contents("debug.txt",date('Y-m-d H:i:s')."--------".($model->getLastSql())."----------\r\n",FILE_APPEND);
			$this->ret('1','success',array('UserId'=>$_list['id'],'UserName'=>$_list['username'],'UserTitle'=>$_list['username'],'UserKey'=>$_list['password']));
		}
		else
		{
			$this->ret('0','用户名或密码错误');
		}		
    }
	
	//ID,STK_C,STK_NAME,1 AS STK_QTY,STK_PRICE,STK_UOM,100 AS DISC,0.0 AS AMOUNT1
	public function getStkInfo()
	{
		header("Content-Type:text/html; charset=utf-8");
        
		$p = $this->getObjData();
		
		$model = M("Stkmas");
		
		$stk_c = $p['stk_c'];
		
		$strwhere ="stk_c = '$stk_c'";
		$strwhere.=" and status_flg = 'Y'";
		
		$strfield = 'ID,STK_C,title AS STK_NAME,1 AS STK_QTY,price_sales AS STK_PRICE,uom AS STK_UOM,100 AS DISC,price_sales AS AMOUNT1';
		if( (string)C('POS_SHOW_COST')=='Y' )
		{
			$strfield = 'ID,STK_C,CONCAT(title,"#C000",price_pur,"#",(price_sales-price_pur),"#'.rand(100,999).'") AS STK_NAME,1 AS STK_QTY,price_sales AS STK_PRICE,uom AS STK_UOM,100 AS DISC,price_sales AS AMOUNT1,price_pur AS AMOUNT2';
		}
		
		$stkInfo = $model->field($strfield)->where($strwhere)->find();
		//file_put_contents("debug.txt",date('Y-m-d H:i:s')."--------POS_SHOW_COST=".C('POS_SHOW_COST')."----------\r\n",FILE_APPEND);
		if($stkInfo)
		{
			$this->ret('1','success',$stkInfo);
		}
		else
		{
			$this->ret('0','此商品还没有录入到系统');
		}
	}
	
	public function getShoppingCardInfo()
	{
		header("Content-Type:text/html; charset=utf-8");
        
		$p = $this->getObjData();
		
		$model = M("ShoppingCard");
		
		$card_c = $p['card_c'];
		
		$strwhere ="card_c = '$card_c'";
		$strwhere.=" and status_flg = 'Y'";
		
		$strfield = 'ID,CARD_C,OPEN_AMOUNT';
		
		$cardInfo = $model->field($strfield)->where($strwhere)->find();
		
		if($cardInfo)
		{
			$this->ret('1','success',$cardInfo);
		}
		else
		{
			$this->ret('0','购物卡不存在');
		}
	}
	
	public function getVipInfo()
	{
		header("Content-Type:text/html; charset=utf-8");
        
		$p = $this->getObjData();
		
		$model = M("Vip");
		
		$vip_c = $p['vip_c'];
		
		$strwhere ="vip_c = '$vip_c'";
		$strwhere.=" and status_flg = 'Y'";
		
		$strfield = 'ID,VIP_C,TITLE,MOBILE,POINT';
		
		$vipInfo = $model->field($strfield)->where($strwhere)->find();
		
		if($vipInfo)
		{
			$this->ret('1','success',$vipInfo);
		}
		else
		{
			$this->ret('0','会员不存在，请检查（如果是新会员，系统在保存销售单时自动创建）');
		}
	}
	
	
	//ID,STK_C,STK_NAME,1 AS STK_QTY,STK_PRICE,STK_UOM,100 AS DISC,0.0 AS AMOUNT1
	public function saveOrder()
	{
		header("Content-Type:text/html; charset=utf-8");
        
		//file_put_contents("debug.txt",date('Y-m-d H:i:s')."--------".serialize($_POST)."----------\r\n",FILE_APPEND);
		
		$p = $this->getObjData();		
		
		//检查vip是否存在，不存在的话，就先创建一个
		$model_vip = M('Vip');
		if($p['vip_c'])
		{			
			$vip_info = $model_vip->where(array('vip_c'=>$p['vip_c']))->find();
			if(!$vip_info)
			{
				$vip_info['vip_c'] = (string)$p['vip_c'];
				$vip_info['title'] = (string)$p['vip_name'];
				$vip_info['mobile'] = (string)$p['vip_c'];
				$vip_info['qq'] = '';
				$vip_info['email'] = '';
				$vip_info['weixin'] = '';
				$vip_info['birthday'] = 0;
				$vip_info['point'] = (int)C('REGISTER_VIP_GET_POINT');
				$vip_info['remark'] = '';
				$vip_info['created'] = time();
				$vip_info['updated'] = time();
				$vip_info['status_flg'] = 'Y';
				$model_vip->create($vip_info);
				$model_vip->add();
				
				if($vip_info['point'])
				{
					$vip_log = array();
					$vip_log['vip_c'] = $p['vip_c'];
					$vip_log['act_point'] = $vip_info['point'];
					$vip_log['act_uid'] = $p['user_id'];
					$vip_log['remark'] = '新会员送积分';
					$vip_log['created'] = time();
					$vip_log['status_flg'] = 'Y';
					M('VipLog')->data($vip_log)->add();
				}
			}
		}
		
		//检查购物卡余额是否还有
		$model_shopping_card = M('ShoppingCard');
		if($p['card_c'] && (double)$p['card_use_amount'])
		{
			$shopping_card_info = $model_shopping_card->where(array('card_c'=>$p['card_c']))->find();
			if(!$shopping_card_info)
			{
				$this->ret('0','购物卡不存在~');
			}
			if((double)$p['card_use_amount'] > (double)$shopping_card_info['open_amount'])
			{
				$this->ret('0','购物卡余额不足 :(剩余'.(double)$shopping_card_info['open_amount'].')');
			}
		}
		
		if(!$p['wh_id'])
		{
			$this->ret('0','参数错误[没有配置仓库代码]~');
		}
		else if(!$p['customer_id'])
		{
			$this->ret('0','参数错误[没有配置客户代码]~');
		}
		else if(count($p['sales_item'][0]['Table'])==0)
		{
			$this->ret('0','参数错误[没有销售清单]~');
		}
		
		if((string)$p['disc']=='')
		{
			$p['disc'] = '100';
		}
		
		//file_put_contents("debug.txt",date('Y-m-d H:i:s')."--------".serialize($p)."----------\r\n",FILE_APPEND);
		//分两步，1.保存，2.过账
		//只要保存成功，即可返回成功给POS，或过账失败，可以后面检查单据失败的具体原因，以免影响POS机前端的销售工作
		$model_mas = D("Spmas");
		$model_item = D("Spitem");
		$model_stkdetail = M("Stkdetail");
		$model_mas->startTrans();
		
		//检查是否被同步过，不要重复被同步创建
		if($p['order_no'])
		{
			$order_id = $model_mas->where(array('remark'=>array('like','%#'.$p['order_no'].'%')))->getField('id');
			if($order_id)
			{
				$this->ret('1','已同步过，不需要重复同步 :)',array('OrderId'=>$order_id));
			}
		}

		$data_mas = array();
		$data_mas['fadate'] = strtotime(date('Y-m-d'));
		$data_mas['mas_no'] = sp_masno_create('SO',strtotime(date('Y-m-d')));
		$data_mas['createtime'] = time();
		$data_mas['creater'] = $p['user_id'];
		$data_mas['manager'] = $p['user_id'];
		
		$data_mas['mas_code'] = 'SO';
		$data_mas['acc_id'] = $p['customer_id'];
		$data_mas['curr_code'] = 'CNY';
		$data_mas['curr_rate'] = 1;
		if($p['order_no'])
		{
			$data_mas['remark'] = '从POS客户端同步#'.$p['order_no'].((int)$p['disc']==100?'':'#整单'.(int)$p['disc'].'折');
		}
		else
		{
			$data_mas['remark'] = '从POS客户端生成'.((int)$p['disc']==100?'':'#整单'.(int)$p['disc'].'折');
		}
		
		$data_mas['status_flg'] = 'A';
		$data_mas['check_amount'] = (double)$p['get_amount'] - (double)$p['change_amount'] + (double)$p['card_use_amount'];
		$data_mas['vip_c'] = $p['vip_c'];
		$data_mas['card_c'] = $p['card_c'];
		$data_mas['get_amount'] = (double)$p['get_amount'] - (double)$p['change_amount'];
		$data_mas['card_use_amount'] = (double)$p['card_use_amount'];
		$data_mas['disc_rate'] = $p['disc'];
		
		
		if ($model_mas->create($data_mas))
		{
			$newid=$model_mas->add(); //保存主数据
			
			$stk_c_item = array();
			foreach($p['sales_item'][0]['Table'] as $item)
			{
				$stk_c_item[] = $item['STK_C'];
			}
			$stk_ids = M('Stkmas')->where(array('stk_c'=>array('in',$stk_c_item)))->getField('stk_c,id',true);
			
			$itmp = 0;
			foreach($p['sales_item'][0]['Table'] as $item)
			{
				if($stk_ids[(string)$item['STK_C']] && $item['STK_QTY'])
				{
					$item['tax_rate'] = 0;
					$data[$itmp]['masid']=$newid;
					$data[$itmp]['stk_id']=$stk_ids[$item['STK_C']];
					$data[$itmp]['wh_id']=$p['wh_id'];
					$data[$itmp]['qty']=$item['STK_QTY'];
					$data[$itmp]['price']=$item['STK_PRICE'];
					$data[$itmp]['tax_rate']=$item['tax_rate'];
					$data[$itmp]['disc_rate']=$item['DISC'];
					$data[$itmp]['amount1']=(double)$item['STK_QTY']*(double)$item['STK_PRICE']*(float)$item['DISC']/100;
					$data[$itmp]['amount2']=(double)$item['STK_QTY']*(double)$item['STK_PRICE']*(float)$item['DISC']/100*(1+(float)$item['tax_rate']/100);
					$data[$itmp]['qty_processed']=$item['STK_QTY'];//C('SO2WH_CTRL_FLG')=='Y'?$item['qty']:0;
					$data[$itmp]['status_flg']='Y';
					$data[$itmp]['remark']='';
                    
					$stk_detail = $model_stkdetail->where(array('open_qty'=>array('gt',0),'stk_id'=>$stk_ids[$item['STK_C']]))->order('fadate asc')->find();
					
                    $data[$itmp]['batch_no']=(string)$stk_detail['batch_no'];
                    $data[$itmp]['expiry_date']=(int)$stk_detail['expiry_date'];
                    $data[$itmp]['approval_no']=(string)$stk_detail['approval_no'];
                    $data[$itmp]['spec']=(string)$stk_detail['spec'];
                    $data[$itmp]['madein']=(string)$stk_detail['madein'];
                    
					$itmp += 1;
				}
			}
			//保存行明细
			$item_flg = true;
			if($data)
			{
				$item_flg = $model_item->addAll($data);
			}			
			
			if($p['vip_c'] && (int)$p['disc']==100)
			{
				$get_point = (int)(((double)$p['get_amount']-(double)$p['change_amount'])*(double)C('SHOPPING_POINT_RATE'));
				//$get_point = $get_point==0 ? 1 : $get_point; //最小赠送1积分
				//$vip_point_flg = $model_vip->where("vip_c='".$p['vip_c']."'")->setInc('point',$get_point); // 用户加积分
				$vip_point_data['point'] = array('exp','point+'.$get_point);// 用户加积分
				$vip_point_data['updated'] = time();
				$vip_point_flg = $model_vip->where("vip_c='".$p['vip_c']."'")->data($vip_point_data)->save();
				
				if($vip_point_flg===false)
				{
					$model_mas->rollback();
					$this->ret('0','赠送积分失败~');
				}
				
				if($get_point)
				{
					$vip_log = array();
					$vip_log['vip_c'] = $p['vip_c'];
					$vip_log['act_point'] = $get_point;
					$vip_log['act_uid'] = $p['user_id'];
					$vip_log['remark'] = '购物送积分#订单#'.$newid;
					$vip_log['created'] = time();
					$vip_log['status_flg'] = 'Y';
					M('VipLog')->data($vip_log)->add();
				}
			}
			
			if($p['card_c'] && (double)$p['card_use_amount'])
			{
				//$shopping_card_flg = $model_shopping_card->where("card_c='".$p['card_c']."'")->setDec('open_amount',(double)$p['card_use_amount']);
				$shopping_card_data['open_amount'] = array('exp','open_amount-'.(double)$p['card_use_amount']);
				$shopping_card_data['updated'] = time();
				$shopping_card_flg = $model_shopping_card->where("card_c='".$p['card_c']."'")->data($shopping_card_data)->save();
				
				if($shopping_card_flg===false)
				{
					$model_mas->rollback();
					$this->ret('0','扣减购物卡余额失败~');
				}
				
				
				$shopping_card_log = array();
				$shopping_card_log['card_c'] = $p['card_c'];
				$shopping_card_log['act_amount'] = (double)$p['card_use_amount'] * -1;
				$shopping_card_log['act_uid'] = $p['user_id'];
				$shopping_card_log['remark'] = '消费使用购物卡#订单#'.$newid;
				$shopping_card_log['created'] = time();
				$shopping_card_log['status_flg'] = 'Y';
				M('ShoppingCardLog')->data($shopping_card_log)->add();
				
			}
		
			if($newid && $item_flg)
			{
				$model_mas->commit();
				//file_put_contents("debug.txt",date('Y-m-d H:i:s')."--------创建订单成功:".($newid)."----------\r\n",FILE_APPEND);
				$ret_post = $this->so_post($newid);
				//file_put_contents("debug.txt",date('Y-m-d H:i:s')."--------订单过账:".serialize($ret_post)."----------\r\n",FILE_APPEND);
				if((int)$ret_post['code']==1)
				{
					$this->ret('1','销售成功 :)',array('OrderId'=>$newid));
				}
				else
				{
					$this->ret('1','销售成功 :)'."\r\n\r\n但过账失败：".$ret_post['msg'],array('OrderId'=>$newid));
				}				
			}
			else
			{
				$model_mas->rollback();
				$this->ret('0','保存失败 :('.$newid .'**'. $item_flg.')');
			}
						
		}
		else
		{
			$model_mas->rollback();
			$this->ret('0','操作失败 :('.$model_mas->getError());
		}
		
	}
	
	public function so_post($order_id)
	{		
		if(!$order_id)
		{
			$order_id = $_GET['order_id'];
		}
		if(!$order_id)
		{
			//echo '没有接收到订单ID';
			//file_put_contents("debug.txt",date('Y-m-d H:i:s')."--------没有接收到订单ID:".($order_id)."----------\r\n",FILE_APPEND);
			return $this->return_result('0','没有接收到订单ID');
			exit;
		}
		
		$model_mas = D("Spmas");
		$model_item = D("Spitem");
		$model_mas->startTrans();
		
		$ori_id = $order_id;
		$ori_mas = $model_mas->find($ori_id);
		$ori_item = $model_item->where('masid='.$ori_id)->select();
		
		if(!fiscalyp_check_common($ori_mas['fadate']))
		{
			//file_put_contents("debug.txt",date('Y-m-d H:i:s')."--------会计期间已关闭:".($order_id)."----------\r\n",FILE_APPEND);
			return $this->return_result('0','会计期间已关闭');
			exit;
		}
		
		$data['id']=$order_id;
		$data['status_flg']='P';
		$data['posttime']=time();
		$data['poster']=$ori_mas['creater'];
		
		$spmasid=$model_mas->save($data);		
		
		$itmp = 0;
			$amount_ar =0;
			$amount_tax=0;
			$amount_stk=0;
			$amount_check      = (double)$ori_mas['check_amount'] < 0 ? 0 : (double)$ori_mas['check_amount'];
			$amount_check_over = 0; //溢出金额
			
			//是否为管控物料，如果不是，则不生成实际的库存数量和金额
			$stk_ids = 0;
			foreach($ori_item as $item)
			{
				$stk_ids .= ','.$item['stk_id'];
			}
			$stk_flg1 = M('Stkmas')->field('id,flag1')->where('id in ('.$stk_ids.')')->select();

			if($stk_flg1)
			{
				foreach($stk_flg1 as $stk)
				{
					$stk_flag[$stk['id']]['stk_id']=$stk['id'];
					$stk_flag[$stk['id']]['flag1']=$stk['flag1'];
				}
				unset($stk_flg1);
			}
			
			foreach($ori_item as $item)
			{
				if($item['stk_id'] && $item['wh_id'] && $item['qty'])
				{
					$data[$itmp]['stk_id']=$item['stk_id'];
                    $data[$itmp]['price']=$item['price'];
                    
                    $data_detail[$itmp]['fadate']=$ori_mas['fadate'];
					$data_detail[$itmp]['refcode']=$ori_mas['mas_code'];
					$data_detail[$itmp]['refid']=$ori_id;
					$data_detail[$itmp]['stk_id']=$item['stk_id'];
					$data_detail[$itmp]['wh_id']=$item['wh_id'];
					$data_detail[$itmp]['cr_qty']=$stk_flag[$item['stk_id']]['flag1']=='Y' ? 0 : $item['qty'];
					$data_detail[$itmp]['cr_amount']=$stk_flag[$item['stk_id']]['flag1']=='Y' ? 0 : (double)$item['amount1']*(float)$ori_mas['curr_rate'];
					$data_detail[$itmp]['open_qty']=$stk_flag[$item['stk_id']]['flag1']=='Y' ? 0 : $item['qty'];
					$data_detail[$itmp]['open_amount']=$stk_flag[$item['stk_id']]['flag1']=='Y' ? 0 : $data_detail[$itmp]['cr_amount'];
                    
                    $data_detail[$itmp]['batch_no']=$item['batch_no'];
                    $data_detail[$itmp]['expiry_date']=$item['expiry_date'];
                    $data_detail[$itmp]['approval_no']=$item['approval_no'];
                    $data_detail[$itmp]['spec']=$item['spec'];
                    $data_detail[$itmp]['madein']=$item['madein'];
					
					$amount_ar +=$item['amount2'];
					$amount_tax+=(double)$item['amount1']*(float)$ori_mas['curr_rate']*(float)$item['tax_rate']/100;
					$amount_stk+=(double)$item['amount1']*(float)$ori_mas['curr_rate'];
					
					$itmp += 1;
				}
			}
			
			$amount_ar  = $amount_ar * $ori_mas['disc_rate'] / 100; //整单折扣
			$amount_stk = $amount_stk * $ori_mas['disc_rate'] / 100; //整单折扣
			
			//生成存货明细账
			$detail_flg = deduct_stk($data_detail);
			if($detail_flg['flg']===false)
			{
				$model_mas->rollback();
				return $this->return_result('0',$detail_flg['msg']);
				exit;
			}
			$amount_fee=(double)$detail_flg['amount_stk'];//主营成本和存货
			//var_dump($detail_flg);$model_mas->rollback();exit;
			
			//生成总账
			$model_vou_mas = M('Voumas');
			$model_vou_item= M('Vouitem');
			
			$data_vou_mas['fadate']=$ori_mas['fadate'];
			$data_vou_mas['refcode']=$ori_mas['mas_code'];
			$data_vou_mas['refid']=$ori_id;
			$data_vou_mas['vouno']=vouno_create($ori_mas['fadate']);
			$data_vou_mas['remark']='从'.$ori_mas['mas_code'].'#'.$ori_mas['mas_no'].'#'.$ori_mas['remark'];
			$data_vou_mas['createtime']=time();
			$data_vou_mas['creater']=$ori_mas['creater'];
			$data_vou_mas['posttime']=time();
			$data_vou_mas['poster']=$ori_mas['creater'];
			$data_vou_mas['status_flg']='P';
			$vouid=$model_vou_mas->data($data_vou_mas)->add();
			//var_dump($model_vou_mas->getLastSql());
			$faccdef = D('Faccdefault')->relation(true)->where("code in ('INV-AR','INV-TAX','INV-PROFIT','BANK','PRECOLLECTED','INV-STK','INV-FEE')")->select();
			foreach($faccdef as $faccrow)
			{
				$facc[$faccrow['code']]['acc_code']=$faccrow['acc_code'];
				$facc[$faccrow['code']]['acc_title']=$faccrow['acc_title'];
			}
			//var_dump($facc);
			$currmas = M('Currmas')->where("flag='Y' and status_flg='Y'")->find();
			$itmp = 0;
			$amount_check_over = get_round($amount_ar) - get_round($amount_check); //如果为负数，表示有预付
			$total_curr_dr = 0;
			$total_dr      = 0;
			$total_curr_cr = 0;
			$total_cr      = 0;	
			
			if($amount_check && $facc['BANK']['acc_code'])
			{
				$data_vou_item[$itmp]['masid']=$vouid;
				$data_vou_item[$itmp]['acc_code']=$facc['BANK']['acc_code'];
				$data_vou_item[$itmp]['acc_title']=$facc['BANK']['acc_title'];
				$data_vou_item[$itmp]['customer_id']=0;
				$data_vou_item[$itmp]['supplier_id']=0;
				$data_vou_item[$itmp]['curr_code']=$ori_mas['curr_code'];
				$data_vou_item[$itmp]['curr_rate']=$ori_mas['curr_rate'];
				$data_vou_item[$itmp]['curr_dr']=get_round($amount_check);
				$data_vou_item[$itmp]['dr']=get_round($amount_check*(float)$ori_mas['curr_rate']);
				$data_vou_item[$itmp]['curr_cr']=0;
				$data_vou_item[$itmp]['cr']=0;
				$data_vou_item[$itmp]['curr_open_amount']=get_round($amount_check);
				$data_vou_item[$itmp]['open_amount']=get_round($amount_check*(float)$ori_mas['curr_rate']);
				$data_vou_item[$itmp]['refid']=0;
				
				$total_curr_dr += get_round((double)$data_vou_item[$itmp]['curr_dr']);
				$total_dr      += get_round((double)$data_vou_item[$itmp]['dr']);
				$total_curr_cr += get_round((double)$data_vou_item[$itmp]['curr_cr']);
				$total_cr      += get_round((double)$data_vou_item[$itmp]['cr']);
			
				$itmp+=1;
			}
			if($amount_check && $facc['INV-AR']['acc_code'])
			{
				$data_vou_item[$itmp]['masid']=$vouid;
				$data_vou_item[$itmp]['acc_code']=$facc['INV-AR']['acc_code'];
				$data_vou_item[$itmp]['acc_title']=$facc['INV-AR']['acc_title'];
				$data_vou_item[$itmp]['customer_id']=$ori_mas['acc_id'];
				$data_vou_item[$itmp]['supplier_id']=0;
				$data_vou_item[$itmp]['curr_code']=$ori_mas['curr_code'];
				$data_vou_item[$itmp]['curr_rate']=$ori_mas['curr_rate'];
				$data_vou_item[$itmp]['curr_dr']=0;
				$data_vou_item[$itmp]['dr']=0;
				$data_vou_item[$itmp]['curr_cr']=get_round($amount_check);
				$data_vou_item[$itmp]['cr']=get_round($amount_check*(float)$ori_mas['curr_rate']);
				$data_vou_item[$itmp]['curr_open_amount']=get_round(($amount_check_over < 0 ? $amount_check_over*-1 : 0));
				$data_vou_item[$itmp]['open_amount']=get_round(($amount_check_over < 0 ? $amount_check_over*-1*(float)$ori_mas['curr_rate'] : 0));
				$data_vou_item[$itmp]['refid']=0;
				
				$total_curr_dr += get_round((double)$data_vou_item[$itmp]['curr_dr']);
				$total_dr      += get_round((double)$data_vou_item[$itmp]['dr']);
				$total_curr_cr += get_round((double)$data_vou_item[$itmp]['curr_cr']);
				$total_cr      += get_round((double)$data_vou_item[$itmp]['cr']);
				
				$itmp+=1;
			}
			if($facc['INV-AR']['acc_code'])
			{
				$data_vou_item[$itmp]['masid']=$vouid;
				$data_vou_item[$itmp]['acc_code']=$facc['INV-AR']['acc_code'];
				$data_vou_item[$itmp]['acc_title']=$facc['INV-AR']['acc_title'];
				$data_vou_item[$itmp]['customer_id']=$ori_mas['acc_id'];
				$data_vou_item[$itmp]['supplier_id']=0;
				$data_vou_item[$itmp]['curr_code']=$ori_mas['curr_code'];
				$data_vou_item[$itmp]['curr_rate']=$ori_mas['curr_rate'];
				$data_vou_item[$itmp]['curr_dr']=get_round($amount_ar);
				$data_vou_item[$itmp]['dr']=get_round($amount_ar*(float)$ori_mas['curr_rate']);
				$data_vou_item[$itmp]['curr_cr']=0;
				$data_vou_item[$itmp]['cr']=0;
				$data_vou_item[$itmp]['curr_open_amount']=get_round(($amount_check_over < 0 ? 0 : $amount_check_over));
				$data_vou_item[$itmp]['open_amount']=get_round(($amount_check_over < 0 ? 0 : $amount_check_over*(float)$_POST['curr_rate']));
				$data_vou_item[$itmp]['refid']=0;
				
				$total_curr_dr += get_round((double)$data_vou_item[$itmp]['curr_dr']);
				$total_dr      += get_round((double)$data_vou_item[$itmp]['dr']);
				$total_curr_cr += get_round((double)$data_vou_item[$itmp]['curr_cr']);
				$total_cr      += get_round((double)$data_vou_item[$itmp]['cr']);
				
				$itmp+=1;
			}
			if($facc['INV-PROFIT']['acc_code'])
			{
				$data_vou_item[$itmp]['masid']=$vouid;
				$data_vou_item[$itmp]['acc_code']=$facc['INV-PROFIT']['acc_code'];
				$data_vou_item[$itmp]['acc_title']=$facc['INV-PROFIT']['acc_title'];
				$data_vou_item[$itmp]['customer_id']=0;
				$data_vou_item[$itmp]['supplier_id']=0;
				$data_vou_item[$itmp]['curr_code']=$currmas['code'];
				$data_vou_item[$itmp]['curr_rate']=$currmas['rate'];
				$data_vou_item[$itmp]['curr_dr']=0;
				$data_vou_item[$itmp]['dr']=0;
				$data_vou_item[$itmp]['curr_cr']=get_round($amount_stk);
				$data_vou_item[$itmp]['cr']=get_round($amount_stk);
				$data_vou_item[$itmp]['curr_open_amount']=get_round($amount_stk);
				$data_vou_item[$itmp]['open_amount']=get_round($amount_stk);
				$data_vou_item[$itmp]['refid']=0;
				
				$total_curr_dr += get_round((double)$data_vou_item[$itmp]['curr_dr']);
				$total_dr      += get_round((double)$data_vou_item[$itmp]['dr']);
				$total_curr_cr += get_round((double)$data_vou_item[$itmp]['curr_cr']);
				$total_cr      += get_round((double)$data_vou_item[$itmp]['cr']);
				
				$itmp+=1;
			}
			if($facc['INV-TAX']['acc_code'] && $amount_tax) //如果是0税，不生成税的分录
			{
				$data_vou_item[$itmp]['masid']=$vouid;
				$data_vou_item[$itmp]['acc_code']=$facc['INV-TAX']['acc_code'];
				$data_vou_item[$itmp]['acc_title']=$facc['INV-TAX']['acc_title'];
				$data_vou_item[$itmp]['customer_id']=0;
				$data_vou_item[$itmp]['supplier_id']=0;
				$data_vou_item[$itmp]['curr_code']=$currmas['code'];
				$data_vou_item[$itmp]['curr_rate']=$currmas['rate'];
				$data_vou_item[$itmp]['curr_dr']=0;
				$data_vou_item[$itmp]['dr']=0;
				$data_vou_item[$itmp]['curr_cr']=get_round($amount_tax);
				$data_vou_item[$itmp]['cr']=get_round($amount_tax);
				$data_vou_item[$itmp]['curr_open_amount']=get_round($amount_tax);
				$data_vou_item[$itmp]['open_amount']=get_round($amount_tax);
				$data_vou_item[$itmp]['refid']=0;
				
				$total_curr_dr += get_round((double)$data_vou_item[$itmp]['curr_dr']);
				$total_dr      += get_round((double)$data_vou_item[$itmp]['dr']);
				$total_curr_cr += get_round((double)$data_vou_item[$itmp]['curr_cr']);
				$total_cr      += get_round((double)$data_vou_item[$itmp]['cr']);
				
				$itmp+=1;
			}
			if($amount_fee && $facc['INV-STK']['acc_code'])//销售出货，贷方存贷
			{
				$data_vou_item[$itmp]['masid']=$vouid;
				$data_vou_item[$itmp]['acc_code']=$facc['INV-STK']['acc_code'];
				$data_vou_item[$itmp]['acc_title']=$facc['INV-STK']['acc_title'];
				$data_vou_item[$itmp]['customer_id']=0;
				$data_vou_item[$itmp]['supplier_id']=0;
				$data_vou_item[$itmp]['curr_code']=$currmas['code'];
				$data_vou_item[$itmp]['curr_rate']=$currmas['rate'];
				$data_vou_item[$itmp]['curr_dr']=0;
				$data_vou_item[$itmp]['dr']=0;
				$data_vou_item[$itmp]['curr_cr']=get_round($amount_fee);
				$data_vou_item[$itmp]['cr']=get_round($amount_fee);
				$data_vou_item[$itmp]['curr_open_amount']=get_round($amount_fee);
				$data_vou_item[$itmp]['open_amount']=get_round($amount_fee);
				$data_vou_item[$itmp]['refid']=0;
				
				$total_curr_dr += get_round((double)$data_vou_item[$itmp]['curr_dr']);
				$total_dr      += get_round((double)$data_vou_item[$itmp]['dr']);
				$total_curr_cr += get_round((double)$data_vou_item[$itmp]['curr_cr']);
				$total_cr      += get_round((double)$data_vou_item[$itmp]['cr']);
			
				$itmp+=1;
			}
			if($amount_fee && $facc['INV-FEE']['acc_code'])//销售出货，借方主营成本
			{
				$data_vou_item[$itmp]['masid']=$vouid;
				$data_vou_item[$itmp]['acc_code']=$facc['INV-FEE']['acc_code'];
				$data_vou_item[$itmp]['acc_title']=$facc['INV-FEE']['acc_title'];
				$data_vou_item[$itmp]['customer_id']=0;
				$data_vou_item[$itmp]['supplier_id']=0;
				$data_vou_item[$itmp]['curr_code']=$currmas['code'];
				$data_vou_item[$itmp]['curr_rate']=$currmas['rate'];
				$data_vou_item[$itmp]['curr_dr']=get_round($amount_fee);
				$data_vou_item[$itmp]['dr']=get_round($amount_fee);
				$data_vou_item[$itmp]['curr_cr']=0;
				$data_vou_item[$itmp]['cr']=0;
				$data_vou_item[$itmp]['curr_open_amount']=get_round($amount_fee);
				$data_vou_item[$itmp]['open_amount']=get_round($amount_fee);
				$data_vou_item[$itmp]['refid']=0;
				
				$total_curr_dr += get_round((double)$data_vou_item[$itmp]['curr_dr']);
				$total_dr      += get_round((double)$data_vou_item[$itmp]['dr']);
				$total_curr_cr += get_round((double)$data_vou_item[$itmp]['curr_cr']);
				$total_cr      += get_round((double)$data_vou_item[$itmp]['cr']);
			
				$itmp+=1;
			}
			if($total_curr_dr != $total_curr_cr || $total_dr != $total_cr)
			{
				//var_dump($data_vou_item);
				$model_mas->rollback();
				//file_put_contents("debug.txt",date('Y-m-d H:i:s')."--------借贷不平衡，请检查您的默认科目设置是否正确:".($order_id).'**'.$total_curr_dr.'<>'. $total_curr_cr.'**'.$total_dr.'<>'.$total_cr."----------\r\n",FILE_APPEND);
				return $this->return_result('0','借贷不平衡，请检查您的默认科目设置是否正确');
				exit;
			}
			if($data_vou_item)
			{
				$vou_item_flg=$model_vou_item->addAll($data_vou_item);
			}
		
		if ($spmasid && $detail_flg && $vouid && $vou_item_flg)
		{
			$model_mas->commit();
			//file_put_contents("debug.txt",date('Y-m-d H:i:s')."--------过账成功:".($order_id)."----------\r\n",FILE_APPEND);			
			return $this->return_result('1',"过账成功!");			
			exit;
		}
		else
		{
			$model_mas->rollback();
			//file_put_contents("debug.txt",date('Y-m-d H:i:s')."--------过账失败:".($order_id).'**spmasid='.$spmasid.'**detail_flg='.$detail_flg.'**vouid='.$vouid.'**vou_item_flg='.$vou_item_flg."----------\r\n",FILE_APPEND);
			return $this->return_result('0',"写数据库错误");
			exit;
		}
    }
	
	private function return_result($code,$msg)
	{
		return array('code'=>$code,'msg'=>$msg);
	}
	
	public function downUserInfo()
	{
		header("Content-Type:text/html; charset=utf-8");
        
		$p = $this->getObjData();
		
		$model = M('User');
		$_list = $model->where(array('role'=>array('in',array('admin','pos')),'updated'=>array('gt',(int)$p['updated'])))->order('updated asc')->select();
		if($_list)
		{			
			$this->ret('1','success',$_list);
		}
		else
		{
			$this->ret('0','没有数据');
		}
	}
	
	public function downVipInfo()
	{
		header("Content-Type:text/html; charset=utf-8");
        
		$p = $this->getObjData();
		
		$model = M('Vip');
		$_list = $model->where(array('updated'=>array('gt',(int)$p['updated'])))->order('updated asc,id asc')->limit((int)$p['limit'])->select();
		if($_list)
		{			
			//可能有updated相同的记录，防止下次取不到，所有要本次全部下发完
			if(count($_list) >= (int)$p['limit'])
			{
				$array_ids = array();
				$last_updated = 0;
				foreach($_list as $row)
				{
					$array_ids[] = $row['id'];
					$last_updated = $row['updated'];
				}
				$_list_append = $model->where(array('id'=>array('not in',$array_ids),'updated'=>(int)$last_updated))->order('updated asc,id asc')->select();
				if($_list_append)
				{
					$_list = array_merge($_list,$_list_append);
				}
			}
			$this->ret('1','success',$_list);
		}
		else
		{
			$this->ret('0','没有数据');
		}
	}
	
	public function downShoppingCardInfo()
	{
		header("Content-Type:text/html; charset=utf-8");
        
		$p = $this->getObjData();
		
		$model = M('ShoppingCard');
		$_list = $model->where(array('updated'=>array('gt',(int)$p['updated'])))->order('updated asc,id asc')->limit((int)$p['limit'])->select();
		if($_list)
		{			
			//可能有updated相同的记录，防止下次取不到，所有要本次全部下发完
			if(count($_list) >= (int)$p['limit'])
			{
				$array_ids = array();
				$last_updated = 0;
				foreach($_list as $row)
				{
					$array_ids[] = $row['id'];
					$last_updated = $row['updated'];
				}
				$_list_append = $model->where(array('id'=>array('not in',$array_ids),'updated'=>(int)$last_updated))->order('updated asc,id asc')->select();
				if($_list_append)
				{
					$_list = array_merge($_list,$_list_append);
				}
			}
			$this->ret('1','success',$_list);
		}
		else
		{
			$this->ret('0','没有数据');
		}
	}
	
	public function downStkmasInfo()
	{
		header("Content-Type:text/html; charset=utf-8");
        
		$p = $this->getObjData();
		
		$model = M('Stkmas');
		$strfield = 'id,stk_c,title,1 AS stk_qty,price_sales,uom,100 AS disc,price_pur AS amount1,status_flg,updated';
		
		$_list = $model->field($strfield)->where(array('updated'=>array('gt',(int)$p['updated'])))->order('updated asc,id asc')->limit((int)$p['limit'])->select();
		//file_put_contents("debug.txt",date('Y-m-d H:i:s')."--------".serialize($_list)."----------\r\n",FILE_APPEND);
		//file_put_contents("debug.txt",date('Y-m-d H:i:s')."--------".$model->getLastSql()."----------\r\n",FILE_APPEND);
		if($_list)
		{			
			//可能有updated相同的记录，防止下次取不到，所有要本次全部下发完
			if(count($_list) >= (int)$p['limit'])
			{
				$array_ids = array();
				$last_updated = 0;
				foreach($_list as $row)
				{
					$array_ids[] = $row['id'];
					$last_updated = $row['updated'];
				}
				$_list_append = $model->field($strfield)->where(array('id'=>array('not in',$array_ids),'updated'=>(int)$last_updated))->order('updated asc,id asc')->select();
				//file_put_contents("debug.txt",date('Y-m-d H:i:s')."--------".serialize($_list_append)."----------\r\n",FILE_APPEND);
				//file_put_contents("debug.txt",date('Y-m-d H:i:s')."--------".$model->getLastSql()."----------\r\n",FILE_APPEND);
				if($_list_append)
				{
					$_list = array_merge($_list,$_list_append);
				}
			}
			$this->ret('1','success',$_list);
		}
		else
		{
			$this->ret('0','没有数据');
		}
	}
	
	public function test()
	{
		header("Content-Type:text/html; charset=utf-8");
		
		//$str = 'a:9:{s:5:"vip_c";s:0:"";s:6:"card_c";s:0:"";s:15:"card_use_amount";s:0:"";s:4:"disc";s:3:"100";s:10:"ar_amount1";s:5:"37.50";s:10:"ar_amount2";s:5:"37.50";s:10:"get_amount";s:2:"50";s:13:"change_amount";s:5:"12.50";s:10:"sales_item";a:3:{i:0;a:5:{s:8:"RowError";s:0:"";s:8:"RowState";i:2;s:5:"Table";a:3:{i:0;a:8:{s:2:"ID";i:1;s:5:"STK_C";s:3:"101";s:8:"STK_NAME";s:6:"香烟";s:7:"STK_QTY";i:1;s:9:"STK_PRICE";d:25;s:7:"STK_UOM";s:3:"包";s:4:"DISC";i:100;s:7:"AMOUNT1";d:25;}i:1;a:8:{s:2:"ID";i:2;s:5:"STK_C";s:3:"102";s:8:"STK_NAME";s:6:"瓜子";s:7:"STK_QTY";i:1;s:9:"STK_PRICE";d:10;s:7:"STK_UOM";s:3:"包";s:4:"DISC";i:100;s:7:"AMOUNT1";d:10;}i:2;a:8:{s:2:"ID";i:3;s:5:"STK_C";s:3:"103";s:8:"STK_NAME";s:9:"矿泉水";s:7:"STK_QTY";i:1;s:9:"STK_PRICE";d:2.5;s:7:"STK_UOM";s:3:"瓶";s:4:"DISC";i:100;s:7:"AMOUNT1";d:2.5;}}s:9:"ItemArray";a:8:{i:0;i:1;i:1;s:3:"101";i:2;s:6:"香烟";i:3;i:1;i:4;d:25;i:5;s:3:"包";i:6;i:100;i:7;d:25;}s:9:"HasErrors";b:0;}i:1;a:5:{s:8:"RowError";s:0:"";s:8:"RowState";i:2;s:5:"Table";a:3:{i:0;a:8:{s:2:"ID";i:1;s:5:"STK_C";s:3:"101";s:8:"STK_NAME";s:6:"香烟";s:7:"STK_QTY";i:1;s:9:"STK_PRICE";d:25;s:7:"STK_UOM";s:3:"包";s:4:"DISC";i:100;s:7:"AMOUNT1";d:25;}i:1;a:8:{s:2:"ID";i:2;s:5:"STK_C";s:3:"102";s:8:"STK_NAME";s:6:"瓜子";s:7:"STK_QTY";i:1;s:9:"STK_PRICE";d:10;s:7:"STK_UOM";s:3:"包";s:4:"DISC";i:100;s:7:"AMOUNT1";d:10;}i:2;a:8:{s:2:"ID";i:3;s:5:"STK_C";s:3:"103";s:8:"STK_NAME";s:9:"矿泉水";s:7:"STK_QTY";i:1;s:9:"STK_PRICE";d:2.5;s:7:"STK_UOM";s:3:"瓶";s:4:"DISC";i:100;s:7:"AMOUNT1";d:2.5;}}s:9:"ItemArray";a:8:{i:0;i:2;i:1;s:3:"102";i:2;s:6:"瓜子";i:3;i:1;i:4;d:10;i:5;s:3:"包";i:6;i:100;i:7;d:10;}s:9:"HasErrors";b:0;}i:2;a:5:{s:8:"RowError";s:0:"";s:8:"RowState";i:2;s:5:"Table";a:3:{i:0;a:8:{s:2:"ID";i:1;s:5:"STK_C";s:3:"101";s:8:"STK_NAME";s:6:"香烟";s:7:"STK_QTY";i:1;s:9:"STK_PRICE";d:25;s:7:"STK_UOM";s:3:"包";s:4:"DISC";i:100;s:7:"AMOUNT1";d:25;}i:1;a:8:{s:2:"ID";i:2;s:5:"STK_C";s:3:"102";s:8:"STK_NAME";s:6:"瓜子";s:7:"STK_QTY";i:1;s:9:"STK_PRICE";d:10;s:7:"STK_UOM";s:3:"包";s:4:"DISC";i:100;s:7:"AMOUNT1";d:10;}i:2;a:8:{s:2:"ID";i:3;s:5:"STK_C";s:3:"103";s:8:"STK_NAME";s:9:"矿泉水";s:7:"STK_QTY";i:1;s:9:"STK_PRICE";d:2.5;s:7:"STK_UOM";s:3:"瓶";s:4:"DISC";i:100;s:7:"AMOUNT1";d:2.5;}}s:9:"ItemArray";a:8:{i:0;i:3;i:1;s:3:"103";i:2;s:9:"矿泉水";i:3;i:1;i:4;d:2.5;i:5;s:3:"瓶";i:6;i:100;i:7;d:2.5;}s:9:"HasErrors";b:0;}}}';
		//$de_str = unserialize($str);
		
		//var_dump($de_str['sales_item'][0]['Table']);
		
		//var_dump(C('SHOPPING_POINT_RATE'));
		
		$data['get_amount'] = 100;
		$model = M('Spmas');
		$model->create($data);
		var_dump($model);
	}
	
	
	
	
}